import { createRouter, createWebHistory } from "vue-router";
import { BASE_URL } from "@/config/setting.ts";
import { routes } from "@/router/routes.ts";
import { getToken } from "@/utils/token-utils.ts";

const router = createRouter({
  routes,
  history: createWebHistory(BASE_URL),
});

/**
 * 添加全局前置守卫
 * @author linyn
 * @date 2025/10/16 17:07
 */
router.beforeEach((to) => {
  const token = getToken();

  // 没有 token 且不是登录页
  if (!token && to.path !== "/login") {
    return {
      path: "/login",
      query: to.path === "/" ? {} : { from: to.path },
    };
  }

  // 有 token 但访问登录页，跳转到首页
  if (token && to.path === "/login") {
    return "/home";
  }
  return true;
});

export default router;
